/*
 * @Author: qinuoyun
 * @Date:   2019-11-11 14:10:22
 * @Last Modified by:   qinuoyun
 * @Last Modified time: 2019-11-22 14:02:49
 */


const fs = require('fs');
const path = require('path');
const join = require('path').join;
const md5 = require('js-md5');
const esprima = require('esprima');
const estraverse = require('estraverse');
const escodegen = require('escodegen');
const acorn = require("acorn");
const _objectValue = require('./_objectValue.js');

function getJsonFiles(jsonPath) {
    let jsonFiles = [];

    function findJsonFile(path) {
        let files = fs.readdirSync(path);
        files.forEach(function(item, index) {
            let fPath = join(path, item);
            let stat = fs.statSync(fPath);
            if (stat.isDirectory() === true) {
                findJsonFile(fPath);
            }
            if (stat.isFile() === true) {
                jsonFiles.push(fPath);
            }
        });
    }
    findJsonFile(jsonPath);
    return jsonFiles;
}


class demo {
    //构造函数
    constructor() {
        this.import = [];
        this.data = {};
        this.components = {};
    }
    index() {
        return "这是一个新的API";
    }
    demo() {

        let config = file_get_contents("./api/config.json");
        config = to_array(config);
        let layer = config.config.layer;
        let page = "";
        layer.forEach((item, index) => {
            page += this.set_row(item.attribute);
        })
        let gather = config.attr.gather.models;
        let actions = config.attr.actions.actions;

        let data = {};

        gather.forEach((item, index) => {
            let value = {};
            item.fields.forEach((_item, _index) => {
                value[_item.field] = _item.default;
            })
            data[item.name] = value;
        })

        let methods = {};
        actions.forEach((item, index) => {
            let value = {};
            item.fields.forEach((_item, _index) => {
                value[_item.field] = _item.default;
            })
            data[item.name] = value;
        })

        console.log(data)
        return page;
    }

    demo2() {
        let _model = "";
        let _gather = "";
        let _name = "";
        let _data = "";
        let _where = "";
        let sql = {
            first: `this.$cloud.name("${_name}").where(this.${_where}).first().then(response => {
                this.${_gather} = response;
            });`
            select: `this.$cloud.name("${_name}").where(this.${_where}).page().select().then(response => {
                this.${_gather} = response;
            });`
            delete: `this.$cloud.name("${_name}").where(this.${_where}).delete().then(response => {
                this.$message({
                    message: '删除数据成功！',
                    type: 'success'
                });
            });`
            update: `this.$cloud.name("${_name}").where(this.${_where}).update(this.${_data}).then(response => {
                this.$message({
                    message: '更新数据成功！',
                    type: 'success'
                });
            });`
            insert: `this.$cloud.name("${_name}").insert(this.${_data}).then(response => {
                this.$message({
                    message: '新增数据成功！',
                    type: 'success'
                });
            });`
        }



        /*let config = file_get_contents("./api/config.json");
        config = to_array(config);
        let layer = config.config.layer;
        let page = "";
        layer.forEach((item, index) => {
            page += this.set_row(item.attribute);
        })*/
        return this.set_ast();
        /*console.log(page)
        return page;*/
    }

    /**
     * 设置图层
     * @param {[type]} attribute [description]
     * @param {String} layer     [description]
     */
    set_row(attribute, layer = "") {
        layer = `<el-row gutter="${attribute.gutter}" type="${attribute.type}" justify="${attribute.justify}" align="${attribute.align}" tag="${attribute.tag}">`
        attribute.col.forEach((item, index) => {
            layer += this.set_col(item.attribute, item.components);
        })
        layer += '</el-row>';
        return layer;
    }

    /**
     * 设置栅格
     * @param {[type]} attribute  [description]
     * @param {[type]} components [description]
     * @param {String} layer      [description]
     */
    set_col(attribute, components, layer = '') {
        layer = `<el-col  span="${attribute.span}", offset="${attribute.offset}", push="${attribute.push}", pull="${attribute.pull}", tag="${attribute.tag}">`
        layer += this.set_components(components);
        layer += '</el-col>'
        return layer;
    }

    /**
     * 设置组件
     * @param {[type]} components [description]
     * @param {String} layer      [description]
     */
    set_components(components, layer = '') {
        let patrol = this.get_patrol();
        //console.log("components", components);
        let label = components.handle;
        let model = "data_" + label;
        layer = `<v-${label} v-model="${model}"></v-${label}>`;
        if (patrol[label]) {
            this.import.push(
                ["import", label, "form", patrol[label]]
            )
            this.data[model] = components.attribute;
            this.components["v-" + label] = patrol[label];
        }
        return layer;
    }

    set_ast() {
        let ast = {
            "type": "Program",
            "start": 0,
            "end": 25,
            "body": [{
                "type": "ExportDefaultDeclaration",
                "start": 0,
                "end": 24,
                "declaration": {
                    "type": "ObjectExpression",
                    "start": 15,
                    "end": 23,
                    "properties": []
                }
            }],
            "sourceType": "module"
        }

        let data = {
            components: {
                aaa: 'bbb',
                ccc: 'bbb'
            },
            data: {
                a: '',
                b: { 'a': 1 },
                c: 1,
                d: [1, 2]
            }
        }

        ast.body[0].declaration.properties.push(this.handle_components(data.components));
        ast.body[0].declaration.properties.push(this.handle_data(data.data));

        console.log(escodegen.generate(ast, { comment: true }));
        return ast;
    }

    /**
     * 测试
     * @return {[type]} [description]
     */
    test() {

        console.log(11);
    }

    /**
     * 加载组件
     * @type {Object}
     */
    handle_components(data) {
        let result = {
            "type": "Property",
            "start": 71,
            "end": 91,
            "method": false,
            "shorthand": false,
            "computed": false,
            "key": {
                "type": "Identifier",
                "start": 71,
                "end": 81,
                "name": "components"
            },
            "value": {
                "type": "ObjectExpression",
                "start": 83,
                "end": 91,
                "properties": []
            },
            "kind": "init"
        }

        let _data = [];
        for (var i in data) {
            let v = _objectValue("init", i, data[i]);
            v.value = {
                "type": "Identifier",
                "start": 328,
                "end": 334,
                "name": data[i]
            }
            _data.push(v);
        }

        result.value.properties = _data;

        return result;
    }

    /**
     * 设置数据
     * @return {[type]} [description]
     */
    handle_data(data) {

        let result = {
            "type": "Property",
            "start": 163,
            "end": 205,
            "method": true,
            "shorthand": false,
            "computed": false,
            "key": {
                "type": "Identifier",
                "start": 163,
                "end": 167,
                "name": "data"
            },
            "kind": "init",
            "value": {
                "type": "FunctionExpression",
                "start": 167,
                "end": 205,
                "id": null,
                "expression": false,
                "generator": false,
                "async": false,
                "params": [],
                "body": {
                    "type": "BlockStatement",
                    "start": 170,
                    "end": 205,
                    "body": [{
                        "type": "ReturnStatement",
                        "start": 180,
                        "end": 199,
                        "argument": {
                            "type": "ObjectExpression",
                            "start": 187,
                            "end": 199,
                            "properties": []
                        }
                    }]
                }
            }
        }

        let _data = acorn.parse('let a = ' + to_json(data));


        result.value.body.body[0].argument.properties = _data.body[0].declarations[0].init.properties;

        return result;
    }

    /**
     * 计算属性
     * @type {Object}
     */
    handle_computed() {

    }

    /**
     * 数据监听
     * @type {Object}
     */
    handle_watch() {

    }

    /**
     * 页面加载执行
     * @return {[type]} [description]
     */
    handle_mounted() {

    }

    /**
     * 页面方法
     * @type {Object}
     */
    handle_methods() {

    }

    /**
     * 编译页面
     * @return {[type]} [description]
     */
    compile_page() {

    }

    /**
     * 获取组件池
     * @return {[type]} [description]
     */
    get_patrol() {
        let patrol = {};
        let files = getJsonFiles(ROOT_DIR + DS + "components" + DS + "cloud-tools");
        files.forEach((item, index) => {
            let extname = path.extname(item);
            if (extname == '.vue') {
                let file = ltrim(item, ROOT_DIR + DS);
                let _key = md5(file);
                patrol[_key] = file;
            }
        });
        return patrol;
    }
}


module.exports = demo;